<template>
  <div class="lifecycle-management">
    <div class="header">
      <h2>数据生命周期管理</h2>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="生命周期策略" name="strategy"></el-tab-pane>
        <el-tab-pane label="归档任务管理" name="archive"></el-tab-pane>
        <el-tab-pane label="清理日志" name="log"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 生命周期策略配置 -->
    <div v-if="activeTab === 'strategy'" class="tab-content">
      <div class="actions">
        <el-button type="primary" @click="openStrategyDialog">+ 新建策略</el-button>
      </div>
      <el-table :data="strategyList" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="name" label="策略名称" />
        <el-table-column prop="type" label="数据类型" />
        <el-table-column prop="hotPeriod" label="热数据存储期" />
        <el-table-column prop="coldPeriod" label="冷数据归档期" />
        <el-table-column prop="autoClean" label="自动清理">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.autoClean" type="success">已开启</el-tag>
            <el-tag v-else type="info">未开启</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 'enabled'" type="success">已启用</el-tag>
            <el-tag v-else type="info">已停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="text" @click="editStrategy(scope.$index)">编辑</el-button>
            <el-button type="text" style="color: red" @click="deleteStrategy(scope.$index)">删除</el-button>
            <el-button type="text" v-if="scope.row.status === 'enabled'" @click="toggleStrategy(scope.$index)">停用</el-button>
            <el-button type="text" v-else @click="toggleStrategy(scope.$index)">启用</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 归档任务管理 -->
    <div v-if="activeTab === 'archive'" class="tab-content">
      <div class="actions">
        <el-button type="primary" @click="openArchiveDialog">手动归档</el-button>
      </div>
      <el-table :data="archiveList" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="name" label="归档包名称" />
        <el-table-column prop="dataType" label="数据类型" />
        <el-table-column prop="archiveTime" label="归档时间" />
        <el-table-column prop="dataSize" label="数据量" />
        <el-table-column prop="storagePath" label="存储路径" />
      </el-table>
    </div>

    <!-- 清理日志 -->
    <div v-if="activeTab === 'log'" class="tab-content">
      <div class="actions" style="margin-bottom: 10px;">
        <el-date-picker
          v-model="logFilter.date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="margin-right: 10px;"
        />
        <el-select v-model="logFilter.dataType" placeholder="数据类型" style="width: 150px;">
          <el-option label="全部" value="" />
          <el-option label="时序数据" value="时序数据" />
          <el-option label="业务数据" value="业务数据" />
        </el-select>
        <el-button type="primary" @click="filterLogs" style="margin-left: 10px;">筛选</el-button>
      </div>
      <el-table :data="filteredLogList" style="width: 100%;">
        <el-table-column prop="time" label="清理时间" />
        <el-table-column prop="dataType" label="数据类型" />
        <el-table-column prop="dataName" label="数据名称" />
        <el-table-column prop="dataSize" label="数据量" />
        <el-table-column prop="remark" label="备注" />
      </el-table>
    </div>

    <!-- 新建/编辑策略弹窗 -->
    <el-dialog :title="strategyDialogTitle" :visible.sync="strategyDialogVisible" width="500px">
      <el-form :model="strategyForm" label-width="120px">
        <el-form-item label="策略名称">
          <el-input v-model="strategyForm.name" />
        </el-form-item>
        <el-form-item label="数据类型">
          <el-select v-model="strategyForm.type" placeholder="请选择">
            <el-option label="时序数据" value="时序数据" />
            <el-option label="业务数据" value="业务数据" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="strategyForm.type === '时序数据'" label="热数据存储期">
          <el-input v-model="strategyForm.hotPeriod" placeholder="如 30天" />
          <span class="desc">存储于SSD硬盘</span>
        </el-form-item>
        <el-form-item v-if="strategyForm.type === '时序数据'" label="冷数据归档期">
          <el-input v-model="strategyForm.coldPeriod" placeholder="如 180天" />
          <span class="desc">迁移至HDD硬盘</span>
        </el-form-item>
        <el-form-item v-if="strategyForm.type === '时序数据'" label="自动清理">
          <el-checkbox v-model="strategyForm.autoClean">自动清理超期数据</el-checkbox>
        </el-form-item>
        <el-form-item v-if="strategyForm.type === '业务数据'" label="保留时长">
          <el-input v-model="strategyForm.hotPeriod" placeholder="如 2年" />
        </el-form-item>
        <el-form-item v-if="strategyForm.type === '业务数据'" label="到期处理">
          <el-input value="到期自动标记为归档状态" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="strategyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveStrategy">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 手动归档弹窗 -->
    <el-dialog title="手动归档" :visible.sync="archiveDialogVisible" width="500px">
      <el-form :model="archiveForm" label-width="120px">
        <el-form-item label="数据类型">
          <el-select v-model="archiveForm.dataType" placeholder="请选择">
            <el-option label="时序数据" value="时序数据" />
            <el-option label="业务数据" value="业务数据" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据名称">
          <el-input v-model="archiveForm.dataName" placeholder="如 历史设备运行数据" />
        </el-form-item>
        <el-form-item label="数据量">
          <el-input v-model="archiveForm.dataSize" placeholder="如 100MB" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="archiveDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveArchive">归 档</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'DataLifecycleManagement',
  data() {
    return {
      activeTab: 'strategy',
      // 策略配置
      strategyList: [],
      strategyDialogVisible: false,
      strategyDialogTitle: '新建策略',
      strategyForm: {
        name: '',
        type: '',
        hotPeriod: '',
        coldPeriod: '',
        autoClean: false,
        status: 'enabled'
      },
      editingStrategyIndex: null,
      // 归档任务
      archiveList: [],
      archiveDialogVisible: false,
      archiveForm: {
        dataType: '',
        dataName: '',
        dataSize: ''
      },
      // 清理日志
      logList: [],
      logFilter: {
        date: [],
        dataType: ''
      },
      filteredLogList: []
    }
  },
  created() {
    this.loadData();
    this.filterLogs();
  },
  watch: {
    logList() {
      this.filterLogs();
    }
  },
  methods: {
    // 数据持久化
    loadData() {
      // 策略
      const strategy = localStorage.getItem('lifecycle_strategy');
      if (strategy) {
        this.strategyList = JSON.parse(strategy);
      } else {
        // 默认策略
        this.strategyList = [
          {
            name: '时序数据存储策略',
            type: '时序数据',
            hotPeriod: '30天',
            coldPeriod: '180天',
            autoClean: true,
            status: 'enabled'
          },
          {
            name: '业务数据归档策略',
            type: '业务数据',
            hotPeriod: '2年',
            coldPeriod: '',
            autoClean: false,
            status: 'enabled'
          },
          {
            name: '历史数据清理策略',
            type: '时序数据',
            hotPeriod: '7天',
            coldPeriod: '30天',
            autoClean: false,
            status: 'disabled'
          }
        ];
        localStorage.setItem('lifecycle_strategy', JSON.stringify(this.strategyList));
      }
      // 归档任务
      const archive = localStorage.getItem('lifecycle_archive');
      this.archiveList = archive ? JSON.parse(archive) : [];
      // 清理日志
      const log = localStorage.getItem('lifecycle_log');
      this.logList = log ? JSON.parse(log) : [];
    },
    saveStrategy() {
      if (!this.strategyForm.name || !this.strategyForm.type) {
        this.$message.error('请填写完整信息');
        return;
      }
      if (this.editingStrategyIndex !== null) {
        // 编辑
        this.$set(this.strategyList, this.editingStrategyIndex, { ...this.strategyForm });
      } else {
        // 新建
        this.strategyList.push({ ...this.strategyForm });
      }
      localStorage.setItem('lifecycle_strategy', JSON.stringify(this.strategyList));
      this.strategyDialogVisible = false;
      this.resetStrategyForm();
    },
    editStrategy(index) {
      this.strategyDialogTitle = '编辑策略';
      this.strategyDialogVisible = true;
      this.editingStrategyIndex = index;
      this.strategyForm = { ...this.strategyList[index] };
    },
    deleteStrategy(index) {
      this.$confirm('确定要删除该策略吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.strategyList.splice(index, 1);
        localStorage.setItem('lifecycle_strategy', JSON.stringify(this.strategyList));
      });
    },
    toggleStrategy(index) {
      const status = this.strategyList[index].status;
      this.strategyList[index].status = status === 'enabled' ? 'disabled' : 'enabled';
      localStorage.setItem('lifecycle_strategy', JSON.stringify(this.strategyList));
    },
    openStrategyDialog() {
      this.strategyDialogTitle = '新建策略';
      this.strategyDialogVisible = true;
      this.editingStrategyIndex = null;
      this.resetStrategyForm();
    },
    resetStrategyForm() {
      this.strategyForm = {
        name: '',
        type: '',
        hotPeriod: '',
        coldPeriod: '',
        autoClean: false,
        status: 'enabled'
      };
    },
    // 归档任务
    openArchiveDialog() {
      this.archiveDialogVisible = true;
      this.archiveForm = {
        dataType: '',
        dataName: '',
        dataSize: ''
      };
    },
    saveArchive() {
      if (!this.archiveForm.dataType || !this.archiveForm.dataName || !this.archiveForm.dataSize) {
        this.$message.error('请填写完整信息');
        return;
      }
      const now = new Date();
      const archiveItem = {
        name: `${this.archiveForm.dataName}归档包`,
        dataType: this.archiveForm.dataType,
        archiveTime: now.toLocaleString(),
        dataSize: this.archiveForm.dataSize,
        storagePath: `/object-storage/${this.archiveForm.dataName}_${now.getTime()}.zip`
      };
      this.archiveList.push(archiveItem);
      localStorage.setItem('lifecycle_archive', JSON.stringify(this.archiveList));
      this.archiveDialogVisible = false;
      // 记录日志
      this.logList.push({
        time: now.toLocaleString(),
        dataType: this.archiveForm.dataType,
        dataName: this.archiveForm.dataName,
        dataSize: this.archiveForm.dataSize,
        remark: '归档生成'
      });
      localStorage.setItem('lifecycle_log', JSON.stringify(this.logList));
      this.filterLogs();
    },
    // 清理日志筛选
    filterLogs() {
      let logs = this.logList;
      if (this.logFilter.dataType) {
        logs = logs.filter(l => l.dataType === this.logFilter.dataType);
      }
      if (this.logFilter.date && this.logFilter.date.length === 2) {
        const [start, end] = this.logFilter.date;
        const startTime = new Date(start).getTime();
        const endTime = new Date(end).getTime();
        logs = logs.filter(l => {
          const t = new Date(l.time).getTime();
          return t >= startTime && t <= endTime;
        });
      }
      this.filteredLogList = logs;
    }
  }
}
</script>

<style scoped>
.lifecycle-management {
  background: #fff;
  padding: 24px;
  min-height: 100vh;
}
.header {
  margin-bottom: 20px;
}
.tab-content {
  margin-top: 20px;
}
.actions {
  margin-bottom: 10px;
}
.desc {
  color: #888;
  font-size: 12px;
  margin-left: 8px;
}
</style>
